// 读取文本文件时，遇到了不是float的数字，导致文件没关闭
package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"strconv"
)

func openFile(fileName string) (*os.File, error) {
	fmt.Println("open file: ", fileName)
	return os.Open(fileName)
}

func closeFile(file *os.File) {
	fmt.Println("close file")
	file.Close()
}

func readFileFloats(fileName string) ([]float64, error) {
	file, err := openFile(fileName)
	if err != nil {
		log.Fatal(err)
	}
	defer closeFile(file)

	var numbers []float64
	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		number, err := strconv.ParseFloat(scanner.Text(), 64)
		if err != nil {
			return numbers, err
		}

		numbers = append(numbers, number)
	}

	return numbers, nil
}

func main() {
	fileName := "p020_read_file_defer.txt"
	numbers, err := readFileFloats(fileName)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(numbers)
}
